import Service from '../../core/baseService';

export default class QrService extends Service {
  constructor(ctx) {
    super(ctx);
    this.model = ctx.sassmodel.Qr;
  }

  async getAccessToken() {
    const id = this.ctx.shop_id;
    const wxAppInfo = await this.ctx.model.Shop.findOne({
      where: { id }
    });

    if (wxAppInfo) {
      const access_token = await this.ctx.service.cache.get('access_token')
      if (access_token) {
        return access_token
      }
      const result = await this.ctx.curl(`https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${wxAppInfo.appid}&secret=${wxAppInfo.secret}`,
        { dataType: 'json' });

      if (!result.data.access_token) {
        throw new Error(JSON.stringify(result.data));
      }
      this.ctx.service.cache.set('access_token', result.data.access_token, 7200) //缓存2小时
      return result.data.access_token
    } else {
      return null;
    }

  }

  async detail(id) {
    const result = await this.model.findOne({
      where: { id },
      attributes: ['about', 'address', 'name', 'phone'],
    });
    return result;
  }

}
